﻿using Microsoft.VisualBasic.FileIO;
using RestSharp;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;


namespace Young_Login
{
    class Program
    {
        /*执行登录即可**/

        //MD5加密函数
        public static string GenerateMD5(string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

        //验证码函数
        public static string GetCode(string username, string userwlanip, string wlanacip, string mac)
        {
            var time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            var secret = "Eshore!@#";
            var version = "214";
            var authenticatorToMd5 = version + userwlanip + wlanacip + mac + time + secret;
            var authenticator = (GenerateMD5(authenticatorToMd5)).ToUpper();
            var body = @"{""version"":""214"",""username"": """ + username + @""",""clientip"":""" + userwlanip + @""",""nasip"":""" + wlanacip + @""",""mac"":""" + mac + @""",""timestamp"":" + time + @",""authenticator"":""" + authenticator + @""",""iswifi"":""4060""}";
            var client = new RestClient("http://enet.10000.gd.cn:10001/client/vchallenge");
            client.Timeout = -1;
            client.FollowRedirects = false;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            // var body = @"{""version"":""214"",""username"":""1111"",""clientip"":""10.170.48.215"",""nasip"":""61.146.140.73"",""mac"":""84-A9-38-30-DB-B4"",""timestamp"":1646574938,""authenticator"":""CC1B0FD55B8C896D3D9B190DCEF229A7"",""iswifi"":""4060""}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            string resString = (response.Content).ToString();
            string[] codeOne = resString.Split('"');
            var code = codeOne[3];
            //下面是检查一下返回的参数
            //Console.WriteLine(resString);
            return code;
        }

        //登录函数
        public static string Login(string username, string userwlanip, string wlanacip, string mac, string code, string password)
        {
            var time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            var secret = "Eshore!@#";
            var authenticatorToMd5 = userwlanip + wlanacip + mac + time + code + secret;
            var authenticator = (GenerateMD5(authenticatorToMd5)).ToUpper();
            var client = new RestClient("http://125.88.59.131:10001/client/login");
            client.Timeout = -1;
            client.FollowRedirects = false;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            var body = @"{""username"":""" + username + @""",""password"":""" + password + @""",""clientip"":""" + userwlanip + @""",""nasip"":""" + wlanacip + @""",""mac"":""" + mac + @""",""timestamp"":" + time + @",""authenticator"":""" + authenticator + @""",""iswifi"":""1050"",""verificationcode"":""" + code + @"""}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            string resString = (response.Content).ToString();
            //string[] codeOne = resString.Split('"');
            //var loginRes = codeOne[3];
            //return loginRes;
            return resString;
        }


        //写入参数函数
        public static void WriteFile()
        {
            //"账号>填在这里面>"
            string strHwF = "\t\t    ||";
            string strHwN = "||";
            string strH = "\n\t\t    ===============================================================================\n";
            Console.WriteLine(strH + strHwF + "  填写好信息后，同目录下，登录双击‘Yong Login’，退出双击‘Young Logout’ " + strHwN +"\n" + strHwF + "             登录成功不会有显示，运行太快了，失败会显示！放心！            " + strHwN + "\n" + strHwF + "         参数信息在同目录下的‘配置.txt’下，后期需要在这里改即可！        " + strHwN + strH);
            StreamWriter streamWriter = new StreamWriter("配置.txt");
            Console.WriteLine("请输入账号：");
            string uesrname = Console.ReadLine();
            //string username = username == null ? username : "2222";
            streamWriter.WriteLine("账号>" + uesrname + ">");
            Console.WriteLine("请输入密码：");
            streamWriter.WriteLine("密码>" + Console.ReadLine() + ">");
            Console.WriteLine("请输入拨号设备IP：");
            streamWriter.WriteLine("拨号设备IP>" + Console.ReadLine() + ">");
            Console.WriteLine("请输入服务器IP：");
            streamWriter.WriteLine("服务器IP>" + Console.ReadLine() + ">");
            Console.WriteLine("请输入拨号设备物理地址(Mac)：");
            streamWriter.WriteLine("拨号设备物理地址(Mac)>" + Console.ReadLine() + ">");
            streamWriter.WriteLine("不要删除“ > ” 符号！>改这里面的参数>");
            Console.WriteLine(strH + "请重新打开软件！任意键退出！" + strH);
            Console.ReadKey();
            streamWriter.Flush();
            streamWriter.Close();
        }

        //主程序
        static void Main(string[] args)
        {
            //开始判断参数文件是否存在,存在就直接读取并运行登录函数，不存在就写入在运行登陆函数
            if (FileSystem.FileExists("配置.txt"))
            {
                string ReadConfig = FileSystem.ReadAllText("配置.txt");
                if (ReadConfig.Length == 0)
                {
                    Console.WriteLine("\n\n                          本程序遵循开源协议，仅供学习交流，需要源码请关注公众号：WLCB小破站");
                    WriteFile();
                }
                else if (ReadConfig.Length != 0)
                {
                    //Console.WriteLine("\n\n                       本程序遵循开源协议，仅供学习交流，需要源码请关注公众号：WLCB小破站");
                    //Console.WriteLine("CONFIG FILE IS EXIST !");  //DELETE
                    string[] ConfigArr = ReadConfig.Split('>');
                    string username = ConfigArr[1];
                    string password = ConfigArr[3];
                    string userwlanip = ConfigArr[5];
                    string wlanacip = ConfigArr[7];
                    string mac = ConfigArr[9];
                    string code = GetCode(username, userwlanip, wlanacip, mac);
                    string resLogin = Login(username, userwlanip, wlanacip, mac, code, password);
                    //调试：下面为人为制造错误
                    //string resLogin = "不含‘零’的返回体";

                    //判断是否登录成功；
                    if (resLogin.IndexOf("0") == -1)
                    {
                        Console.WriteLine("\n\n                       本程序遵循开源协议，仅供学习交流，需要源码请关注公众号：WLCB小破站");
                        Console.WriteLine("LOGIN ERROR! \n\rERROR:\n\r" + resLogin);
                        Console.ReadLine();
                    }
                    else 
                    {
                        Console.WriteLine("\n\n                       本程序遵循开源协议，仅供学习交流，需要源码请关注公众号：WLCB小破站");
                        Console.WriteLine("LOGIN ERROR! \n\r注意:\n\r由于天翼校园网就算你的账号错误或不存在他都会返回成功登录参数响应体，成功与否需要你检查网络！" );
                        Console.ReadLine();
                    }

                    //下面是调试代码可删除
                    //Console.WriteLine(ConfigArr[1]);
                    //foreach(string i in ConfigArr)
                    //{
                    //    if(i == "" || i == "\n")
                    //    {
                    //        continue;
                    //    }
                    //    Console.WriteLine(i);
                    //}
                    //Console.ReadLine();   //DELETE
                }
                else
                {
                    Console.WriteLine("Unknown error！Contact Author");
                    Console.WriteLine("\n\n                       本程序遵循开源协议，仅供学习交流，需要源码请关注公众号：WLCB小破站");
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("\n\n                       本程序遵循开源协议，仅供学习交流，需要源码请关注公众号：WLCB小破站");
                Console.WriteLine("NOT HAVE CONFIG FILE !");  //DELETE
                WriteFile();
                Console.ReadLine();
            }
        }
    }
}
